# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
        ans = [100005,-100005]
        # 维护2个指针，一个指向当前节点，一个指向前一个节点，注意这里指向的是普通节点
        pre = head 
        cur = head.next  
        left = -1 #初始化为-1的目的是，一旦是负数，说明还没初始化完毕，并不代表最左侧的极值点
        mid = -1
        right = 1 
        flag = False #表示极值点的数量是否大于等于2
        while cur is not None:
            if cur.next is not None:
                flag1 = cur.val > pre.val and cur.val > cur.next.val #极大值点
                flag2 = cur.val < pre.val and cur.val < cur.next.val
                if flag1 or flag2: #证明是极值点，需要记录坐标
                    if left == -1:
                        left = right #记录最左侧的极值点
                    elif mid == -1: # 算上mid只有2个极值点
                        flag = True
                        mid = right 
                        ans[0] = min(ans[0],mid-left)
                        ans[1] = max(ans[1],mid-left)
                    else: #算上right至少有3个极值点
                        # flag = True
                        ans[0] = min(ans[0],right-mid)
                        ans[1] = max(ans[1],right-left)
                        #最后更新前一个节点,更新mid
                        mid = right
            pre = cur #遍历完当前节点之后，要后移前趋节点和当前节点，一定先移动前趋节点，防止当前节点丢失
            cur = cur.next 
            right += 1
        if not flag:
            return [-1,-1]
        return ans